<?php

class CartAction extends fvAction {

	function __construct () {
	    parent::__construct(fvSite::$Layoult);
	}

    function executeIndex() {
        if (!fvRequest::getInstance()->isXmlHttpRequest()) {
            return self::$FV_OK;
        } else {
            return self::$FV_AJAX_CALL;
        }   
    }

	function executeBlock() {
        if (!fvRequest::getInstance()->isXmlHttpRequest()) {
            return self::$FV_OK;
        } else {
            return self::$FV_AJAX_CALL;
        }   
    }

	function executeOrder() {
        if (!fvRequest::getInstance()->isXmlHttpRequest()) {
            return self::$FV_OK;
        } else {
            return self::$FV_AJAX_CALL;
        }   
    }

	function executeSave() {
		$request = fvRequest::getInstance();
    	if (fvSite::$fvSession->getCustomer()){
    		$Customer = CustomerManager::getInstance()->getByPk(fvSite::$fvSession->getCustomer()->getPk());
    		$n = $request->getRequestParameter("m");
    		$Customer->updateFromRequest($n);
    		if ($Customer->save(false)){
    			fvSite::$fvSession->set('Error', $Customer->getValidationResult());
    		}
    	}
    	else{
    		$Customer = new Customer();
    		$NewPassword = CustomerManager::getInstance()->generatePassword(10);
    		$n = $request->getRequestParameter("m");
    		$n['password1'] = $NewPassword;
    		$n['password'] = $NewPassword;
    		$n['active'] = 1;
    		$request->putRequestParameter('m',$n);
			$n = $request->getRequestParameter("m");
			$className = fvSite::$fvConfig->get('access.user_class');
        	$UserManager = call_user_func(array("{$className}Manager", 'getInstance'));
        	$request = fvRequest::getInstance();
    		$Customer->updateFromRequest($n);
    		if ($Customer->save(false)){
    			$login = $n["email"];
        		$password = md5($n['password']);
        		$LoggedUser = $UserManager->Login($login, $password);
        		fvSite::$fvSession->setCustomer($LoggedUser);
        		$mail = new html_mime_mail();
				$letter = "
	                <html>
	                <body>
	                	Шановний (-а), {$Customer->full_name}!<p>
						Дякуємо за реєстрацію на <a href='http://{$_SERVER["SERVER_NAME"]}/'>Крамниця-А</a>.<br>
						Ваші дані для входу в систему:<br>
						Логін: {$Customer->email}<br>
						Пароль: {$NewPassword}<p> 
						Команда <a href='http://{$_SERVER["SERVER_NAME"]}/'>Крамниця-А</a>.
	                </body>
	                </html>";
				$mail->add_html($letter);
				$mail->build_message("w");
				$mail->SendMail("noreply@kramnyca.info",'Крамниця - А  |  Едине місце актуальних українських товарів',$Customer->email,$Customer->full_name, "Реєстрація на сайті");
    		}
    		else{
    			fvSite::$fvSession->set('Error', $Customer->getValidationResult());
    		}
    	}
		if (fvSite::$fvSession->get('Error')){
    		fvDispatcher::getInstance()->redirect(fvSite::$fvConfig->get('dir_web_root') . $request->getRequestParameter('module') . "/".$request->getRequestParameter('operation'));	
    	}
    	else{
    		$cook = new fvCookie();
		    $vals = $cook->extract();
		    if ($vals["product"])
			foreach ($vals["product"] as $k=>$v){
	    		$Products[$k] = ProductsManager::getInstance()->getByPk($k);
	    		$Products[$k]["count"] = $v;
	    	}
	    	if ($Products)
	    	foreach ($Products as $Product){
	    		if ($Product->in_stock == 'yes' || $Product->in_stock == 'order'){
	    			$ProductsCanOrder[] = array("product_id"=> $Product->getPk() , "count" => $Product->count);
	    			$cook->put("product", array($Product->getPk() => 0));
	    		}
	    	}
	    	$Order = new Order();
	    	$Order->customer_id = fvSite::$fvSession->getCustomer()->getPk();
	    	$Order->products = $ProductsCanOrder;
	    	$Order->address = $n['address'];
	    	$Order->payment = $n['payment'];
	    	$Order->delivery = $n['delivery'];
	    	$Order->info = $n['info'];
	    	$Order->save(false);
	    	$mail = new html_mime_mail();
	    	$delivery = 
			$letter = "
            <html>
                <body>
				<table width='100%' border='0' cellspacing='0' cellpadding='10'>
				  <tr>
					<td colspan='4' align='center'><p>Шановний (-а), {$Customer->full_name}!  Дякуємо за замовлення на <a href=http://{$_SERVER["SERVER_NAME"]}/'>Крамниця-А</a>.</p>
					<p><strong>Ваше замовлення №{$Order->getPk()}</strong></p></td>
				  </tr>
				  <tr>
					<td bgcolor='#CCCCCC'>Назва товару</td>
					<td bgcolor='#CCCCCC'>Ціна</td>
					<td bgcolor='#CCCCCC'>Кількість</td>
					<td bgcolor='#CCCCCC'>Загальна сума</td>
				  </tr>
					";
			$summ = 0;
			foreach ($Order->products as $prod){
				$p = ProductsManager::getInstance()->getByPk($prod["product_id"]);
				$summ += ($p->price-$p->price*$p->discount/100)*$prod["count"];
				$letter .= 
				"
				<tr>
				<td>{$p->title}".(($Product->in_stock == 'order')? ' *' : '')."</td>
				<td>".number_format($p->price-$p->price*$p->discount/100, 2)."</td>
				<td>{$prod["count"]}</td>
				<td>". number_format(($p->price-$p->price*$p->discount/100)*$prod["count"], 2)."</td>
				</tr>
				  <tr>
				<td colspan='4'><hr size='1' noshade></td>
			  </tr>
				";
			}								
			$letter .= 
			"
			</table>
			<br>* - на замовлення 
			<br>Команда <a href='http://{$_SERVER["SERVER_NAME"]}/'>Крамниця-А</a>.
                </body>
                </html>
				";	
			$mail->add_html($letter);
			$mail->build_message("w");
			$mail->SendMail("noreply@kramnyca.info",'Крамниця - А  |  Едине місце актуальних українських товарів',$Customer->email,$Customer->full_name, "Замовлення на сайті");
	    	fvSite::$fvSession->set('order_id', $Order->getPk());
    		fvDispatcher::getInstance()->redirect(fvSite::$fvConfig->get('dir_web_root') . $request->getRequestParameter('module') . "/success");
    	}
    }

	function executeSuccess() {
		if (!fvSite::$fvSession->getCustomer()){
			fvDispatcher::getInstance()->redirect(fvSite::$fvConfig->get('dir_web_root'));
		}
        if (!fvRequest::getInstance()->isXmlHttpRequest()) {
            return self::$FV_OK;
        } else {
            return self::$FV_AJAX_CALL;
        }   
    }
}
?>
